package com.supreme.uploadserver.service.impl;

import com.supreme.uploadserver.service.FileProcService;
import com.supreme.uploadserver.service.IFileCallback;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Slf4j
@Service
public class FileStoreService implements FileProcService {

    private File buildNewFile(String storePath, String originalFilename) {
        String projectPropertyDir = System.getProperty("user.dir");
        File storePathFile = new File(projectPropertyDir + "/" + storePath);
        if (!storePathFile.exists()) {
            storePathFile.mkdirs();
        }

        String suffixName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String newFileName = String.format("%s-%s.%s", UUID.randomUUID(), System.currentTimeMillis(), suffixName);

        return new File(storePathFile, newFileName);
    }

    private Path buildNewFilePath(String storePath, String originalFilename) throws IOException {
        String projectPropertyDir = System.getProperty("user.dir");
        log.info("projectPropertyDir = {}", projectPropertyDir);
        Path storeFilePath = Paths.get(projectPropertyDir, storePath);
        if (!Files.exists(storeFilePath)) {
            Files.createDirectories(storeFilePath);
        }

        String suffixName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String newFileName = String.format("%s-%s.%s", UUID.randomUUID(), System.currentTimeMillis(), suffixName);

        return Paths.get(storeFilePath.toString(), newFileName);
    }

    @Override
    public Path storeUploadFile(String storePath, String originalFilename, IFileCallback fileCallback) throws IOException {
        log.info("storeUploadFile = {}", storePath);
        Path newFilePath = buildNewFilePath(storePath, originalFilename);
        log.info("newFilePath = {}", newFilePath);

        if (fileCallback != null) {
            fileCallback.writeToFile(newFilePath);
        }

        return newFilePath;
    }

    @Override
    public String writeUploadFile(byte[] multipartFileBytes, String storePath, String originalFilename) throws IOException {
        Path newFilePath = buildNewFilePath(storePath, originalFilename);

//        FileOutputStream outputStream = new FileOutputStream(String.format("%s/%s", storePath, newFileName));
        FileOutputStream outputStream = new FileOutputStream(newFilePath.toString());
        outputStream.write(multipartFileBytes);

        return newFilePath.getFileName().toString();
    }
}
